package com.ric.springredis.service;

import com.ric.springredis.entity.RoleEntity;
import com.ric.springredis.repository.RoleRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 创建 JYQ  on  2018/10/30,10:58
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleRepository repository;
    @Resource
    private RedisTemplate<Object,Object> redisTemplate;
    @Cacheable(value = "roleService")
    @Override
    public List<RoleEntity> findAll() {
        System.out.println("RoleServiceImpl.findAll");
        return this.repository.findAll();
    }


    @Cacheable(value = "roleService" , key = "#roleId")
    @Override
    public RoleEntity findOne(Long roleId) {
        System.out.println("RoleServiceImpl.findOne");
        return this.repository.findById(roleId).get();
    }

    @Override
    @CacheEvict(value = "roleService" ,allEntries = true)
//    @CachePut(value = "roleService",key = "#roleEntity.roleId")
    public RoleEntity save(RoleEntity roleEntity) {
        System.out.println("RoleServiceImpl.save");
        RoleEntity save = this.repository.save(roleEntity);
        return save;
    }
    @CacheEvict(value = "roleService" ,allEntries = true)
    @Override
    public Boolean delete(Long roleId) {
        System.out.println("RoleServiceImpl.delete");
        this.repository.deleteById(roleId);
        return true;
    }
    public boolean thumb(Long roleId){
        ZSetOperations<Object, Object> opsForZSet = this.redisTemplate.opsForZSet();
        RoleEntity one = findOne(roleId);
        opsForZSet.incrementScore("thumb:roleId",one,1);
        return  true;
    }
    public  Set<?>  thumbList(){
        ZSetOperations<Object, Object> opsForZSet = this.redisTemplate.opsForZSet();
//        Set<Object> set = opsForZSet.reverseRange("thumb:roleId", 0, 2);
        Set<ZSetOperations.TypedTuple<Object>> scores = opsForZSet.reverseRangeWithScores("thumb:roleId", 0, 2);
        return  scores;

    }
}
